package org.currentcost;


import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.UnsupportedCommOperationException;
import org.currentcost.messages.EnviMessage;
import org.xml.sax.SAXException;

import java.io.IOException;

public class TestReader implements MessageConsumer
{
	private String _portName;

	public TestReader(String portName)
	{
		_portName = portName;
	}

	public static void main(String[] args)
	{
		String portName = "COM9";
		for (int i = 0; i < args.length; i++) {
			String arg = args[i];
			if ("-port".equals(arg)) {
				if (i >= args.length) {
					_usage(1);
				}
				i++;
				portName = args[i];
			}
			else if ("-?".equals(arg) || "-help".equals(arg) || "-h".equals(arg)) {
				_usage(0);
			}
			else {
				_usage(1);
			}
		}

		TestReader testReader = new TestReader(portName);
		try {
			testReader.start();
		}
		catch (Exception e) {
			e.printStackTrace();
			//To change body of catch statement use File | Settings | File Templates.
		}
	}

	private void start()
			throws UnsupportedCommOperationException, IOException, SAXException, PortInUseException, NoSuchPortException
	{
		EnviReader reader = new EnviReader(_portName, this);
		reader.start();
	}

	private static void _usage(int status)
	{
		System.err.println("Usage: TestReader [ -port <COM port name> ]\n");
		System.exit(status);
	}

	@Override
	public void messageReceived(EnviMessage msg)
	{
		System.out.println(msg);
	}
}
